package edu.ynu.se.xiecheng.achitectureclass.project.interceptor;

import edu.ynu.se.xiecheng.achitectureclass.project.util.JwtUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String jwt = authHeader.substring(7);
            try {
                jwtUtils.parseJWT(jwt); // 调用 parseJWT 方法
                return true; // 放行
            } catch (Exception e) {
                // 处理解析失败的情况
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false; // 拦截
            }
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false; // 拦截
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 目标资源方法运行后运行
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 视图渲染完毕后运行, 最后运行
    }
}